package com.tanhua.server.impl;

import cn.hutool.core.collection.CollUtil;
import com.aliyuncs.utils.StringUtils;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.*;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.domain.ErrorResult;
import com.tanhua.model.domain.User;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.UserServiceApi;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class Userservice implements UserServiceApi {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private Visitorsapi visitorsapi;


    @DubboReference
    private UserApi userApi;

    private static final String CODE = "CODE_CHECK_CODE_";
    //取消喜欢
    public void delectLike(Long likeuid) {
        Long userId = UserHolder.getUserId();
        userLikeApi.delectLike(likeuid,userId);

    }
    public PageResult findBytype(Integer type, Integer page, Integer pagesize, String nickname) {
        Long userId = UserHolder.getUserId();
        if (type == 1) {
            //互相喜欢的like集合
            List<UserLike> ltlList = userLikeApi.findLiketolike(type, page, pagesize, nickname, userId);
            List<Long> ids = CollUtil.getFieldValues(ltlList, "userId", Long.class);
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
            List<UserInfoVo> vos = new ArrayList<>();
            for (UserLike userLike : ltlList) {
                UserInfo userInfo1 = map.get(userLike.getUserId());
                if (userInfo1 != null) {
                    UserInfoVo vo = UserInfoVo.init(userInfo1);
                    vo.setMatchRate(99);
                    vos.add(vo);
                }
            }
            return new PageResult(page, pagesize, 0l, vos);
        } else if (type == 2) {
            List<UserLike> mylike = userLikeApi.findMylike(type, page, pagesize, userId);
            List<Long> ids = CollUtil.getFieldValues(mylike, "likeUserId", Long.class);
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
            List<UserInfoVo> vos = new ArrayList<>();
            for (UserLike userLike : mylike) {
                UserInfo userInfo1 = map.get(userLike.getLikeUserId());
                if (userInfo1 != null) {
                    UserInfoVo vo = UserInfoVo.init(userInfo1);
                    vos.add(vo);
                }
            }
            return new PageResult(page, pagesize, 0l, vos);
        } else if (type == 3) {
            List<UserLike> likeMe = userLikeApi.findlikeme(type, page, pagesize, userId);
            List<Long> ids = CollUtil.getFieldValues(likeMe, "userId", Long.class);
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
            List<UserInfoVo> vos = new ArrayList<>();
            for (UserLike userLike : likeMe) {
                UserInfo userInfo1 = map.get(userLike.getLikeUserId());
                if (userInfo1 != null) {
                    UserInfoVo vo = UserInfoVo.init(userInfo1);
                    vos.add(vo);
                }
            }
            return new PageResult(page, pagesize, 0l, vos);

        } else {
            List<Visitors> myLook = visitorsapi.lookMe(type, page, pagesize, userId);
            List<Long> ids = CollUtil.getFieldValues(myLook, "visitorUserId", Long.class);
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
            List<UserInfoVo> vos = new ArrayList<>();
            for (Visitors visitors : myLook) {
                UserInfo userInfo1 = map.get(visitors.getVisitorUserId());
                if (userInfo1 != null) {
                    UserInfoVo vo = UserInfoVo.init(userInfo1);
                    vos.add(vo);
                }
            }
            return new PageResult(page, pagesize, 0l, vos);
        }
    }
    public void sendCode(String phone) {
        //校验用户状态--------------------------
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.checkUserStatus(1, user.getId());
        }
        //1. 生成随机验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2. 调用阿里云发送验证码
        //smsTemplate.sendSms(phone, code);
        //3.将验证码存入redis
        redisTemplate.opsForValue().set(CODE + phone, code, Duration.ofMinutes(5));
    }

    public Map findUser(String phone, String verificationCode) {
        String redisCode = (String) redisTemplate.opsForValue().get(CODE + phone);
        //判断验证码
        if (StringUtils.isEmpty(redisCode) || !verificationCode.equals(redisCode)) {
            throw new RuntimeException("验证码校验失败");
        }

        // 判断用户是否注册
        boolean isNew = false;
        User user = userApi.findByMobile(phone);
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        //登陆成功删除redis验证码
        redisTemplate.delete(CODE + phone);
        //4. 登录成功, 生成token
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);

        //5. 封装数据返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);
        mqMessageService.sendLogMessage(user.getId(), "0101", "up", "");
        return result;

    }

    public Map checkVerificationCode(String verificationCode) {
        String phone = UserHolder.getMobile();
        String redisCode = (String) redisTemplate.opsForValue().get(CODE + phone);
        Map map = new HashMap();
        if (StringUtils.isEmpty(redisCode) || !verificationCode.equals(redisCode)) {
            map.put("verification", false);
        }
        //校验成功 删除验证码
        redisTemplate.delete(CODE + phone);

        map.put("verification", true);
        return map;
    }

    public void savePhone(String phone) {
        User newUser = userApi.findByMobile(phone);
        if (newUser != null) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        String mobile = UserHolder.getMobile();
        User user = userApi.findByMobile(mobile);
        user.setMobile(phone);
        userApi.update(user);
    }

    public Map getcounts(Long userId) {
        //我喜欢的
        Integer loveCount = userLikeApi.myLike(userId);
        //喜欢我的
        Integer fanCount = userLikeApi.likeMe(userId);
        //互相喜欢
        Integer eachLoveCount = userLikeApi.likeTOlike(userId);
        Map map = new HashMap();
        map.put("loveCount", loveCount);
        map.put("fanCount", fanCount);
        map.put("eachLoveCount", eachLoveCount);

        return map;
    }


}